// pages/order-all/order-all.js
import {OrderStatus} from "../../utils/const.js"
const orderService =  require( '../../services/order/orderService.js');
const utils =  require( '../../utils/util.js');
let innerAudioContext = null;

const defaultPageInfo = {
  pageNum: 1,
  pageSize: 12,
  totalSize: null,
  pages: null,
};
const pageSize = 12;
var app = getApp();
let backgroundAudioManager = null;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    tabs: [
      { key: -1, text: '全部' },
      { key: OrderStatus.PENDING_PAYMENT, text: '未付款', info: '' },
      { key: OrderStatus.PENDING_DELIVERY, text: '已付款', info: '' },
      { key: OrderStatus.COMPLETE, text: '已完成', info: '' },
      { key: OrderStatus.PENDING_REFUND, text: '退款/售后', info: '' },
    ],
    currentPageInfo:defaultPageInfo,
    listLoading: 0, // 0: 无操作，1: 加载中，2: 加载完成，3: 加载错误，刷新
    orderList: [],
    orderListReadStatus:[],
    orderListBak: [],
    status: -1,
    emptyImg: 'http://www.breakfast-dinner.xin/chb_eatery_images/empty-order-list.png',
    searchValue: '',
    searchActionText: '',
    activeValues: [0],
    socketHandler: null,
    websocketConnecting: false,
    websocketSendIntervalHandler : null,
  },
  
  onBack() {
    wx.navigateBack()
  },

  onGoHome() {
    wx.reLaunch({
      url: '/pages/home/home',
    });
  },

  onTabChange(e){
    const { value } = e.detail;
    const tab = this.data.tabs.find((v) => v.key === value);
    if (!tab) return;
    var that = this;
    this.setData({status: value,activeValues:[0]}, ()=>{
      that.refreshListAdmin(value);
    })
  },

  refreshListAdmin(status, reset=true){
    var that = this;
    if(1 === this.data.listLoading){
      // busy
      return;
    }
    this.setData({
      listLoading: 1,
    })
    if(reset){
      this.setData({
        orderList: []
      })
    }
    let list = this.data.orderList;
    orderService.getAdminHistoryOrderV2(status, 
      (list.length===0 ? null : list[list.length-1].order.id), 
      pageSize).then((res) => {
      // 1. 检查返回pageNum是否正确
      if(res.data.list.length === 0){
        that.setData({
          listLoading: 2
        })
        return;
      }else{
        that.setData({
          listLoading: 0
        })
      }
      if(list.length !== 0 && list[list.length-1].order.id <= res.data.list[0].order.id){
        // 重复数据
        return ;
      }
      let updateList = res.data.list.map((item) =>  {
        return {readStatus: 0,...item}        
      })
      that.setData({
        orderList: reset?updateList:that.data.orderList.concat(updateList),
        currentPageInfo: res.data
      }, ()=>{})
    }).catch((e)=>{
      that.setData({
        listLoading: 3
      })
    });
  },

  changeHandle(e) {
    const { value } = e.detail;

    if(this.data.orderListBak.length === 0
      || this.data.orderListBak.length < this.data.orderList.length){
      // this.data.orderListBak = JSON.parse(JSON.stringify(this.data.orderList));
      this.data.orderListBak = this.data.orderList;
    }else{
      this.data.orderList = this.data.orderListBak;
    }
    let list = this.data.orderList;
    list = list.filter((item) => (utils.getLastDigits(item.order.orderNo).includes(value)))
    
    this.setData({
      searchValue: value,
      orderList: list,
    });
  },

  focusHandle() {
    this.setData({
      actionText: '×',
    });
  },

  blurHandle() {
    this.setData({
      actionText: '',
    });
  },

  actionHandle() {
    this.setData({
      value: '',
      actionText: '',
    });
  },

  onReTry(){
    console.log('点击了刷新')
    this.refreshListAdmin(this.data.status, false);
  },

  onClickGrid(e){
    let index = e.currentTarget.dataset.index;
    const key = `orderList[${index}].readStatus`;
    this.setData({
      [key]: 0,
    })
  },

  handleCollapseChange(e){
    // let value = e.detail.value[0]; // 获取当前值
    let value = e.currentTarget.dataset.index;
    let activeValues = this.data.activeValues; // 获取当前的 activeValues 数组
    const key = `orderList[${value}].readStatus`;
    this.setData({
      [key]: 0,
    })
  
    if (activeValues.includes(value)) {
      // 如果数组中已存在 value，则移除它
      activeValues = activeValues.filter(item => item !== value);
    } else {
      // 如果数组中不存在 value，则添加它
      activeValues.push(value);
    }
  
    // 更新数据
    this.setData({
      activeValues: activeValues,
    });
  },

  onRefreshAll(){
    this.refreshListAdmin(this.data.status, true);
  },
  onCollapseAll(){
    let activeValues = [];
    for(let i=0; i<this.data.orderList.length; i++){
      activeValues.push(i);
    }
    this.setData({
      activeValues,
    })
  },
  onFoldAll(){
    this.setData({
      activeValues: [],
    })
  },

  onScrollToLower() {
    console.log('-------------onScrollToLower------------------')
    this.refreshListAdmin(this.data.status, false);
  },

  connectWebSocket: function () {
    let socket = wx.connectSocket({
      url: `wss://www.breakfast-dinner.xin/ws/${app.data.loginData.openid}`,
      header:{
        'Authorization': `Bearer ${app.data.loginData.token}`,
      },
      success(res){
        console.log('-------success--------', res)
      },
      fail(e){
        console.log('-------fail--------', e)
      },
      complete(e){
        console.log('-------done--------', e)
      }
    });

    socket.onMessage((message) => {
      let newPaidOrder = false;
      var that = this;
      let result=[];
      console.log(message)
      let respond = JSON.parse(message.data);
      console.log('------收到服务器推送-------', respond);
      if(!respond || respond.length === 0){
        return;
      }
      // 添加未读标志
      result = respond.map((item) =>  {
        return {readStatus: 1,...item} 
      })

      if(result[0].status){
        // 1. 是否有订单状态发生更新
        for(let i=0; i<result.length; i++){
          let item = result[i];
          for(let elem of that.data.orderList){
            if(item.status.id === elem.order.id){
              elem.order.orderStatus = item.status.orderStatus;
              if(elem.order.orderStatus === OrderStatus.PENDING_DELIVERY){
                newPaidOrder = true;
              }
              break;
            }
          }
        }
      }

      // 播放哪种音乐
      if(newPaidOrder){
        innerAudioContext.src = app.data.global_urls.new_msg_voice;
      }else{
        innerAudioContext.src = app.data.global_urls.general_msg_voice;
      }
      innerAudioContext.play();

      if(result[0].order && result[0].orderDetail){
        // 2. 是否有新订单加入
        let maxId;
        if (this.data.orderList.length === 0) {
          maxId = -1;
        } else {
            maxId = this.data.orderList[0].order.id;
        }
        
        result = result.filter((item) => item.order.id > maxId);
        this.data.orderList = result.concat(this.data.orderList);
      }

      // 3. 更新显示
      this.setData({
        orderList: this.data.orderList
      })
    });

    socket.onOpen((res)=>{
      console.log('------------onOpen--------------', res);
      this.setData({
        websocketConnecting: true
      })
    })

    socket.onClose((res) => {
      console.log('------------onClose--------------', res);
      this.setData({
        websocketConnecting: false
      })
    })

    this.data.websocketSendIntervalHandler = setInterval(()=>{
      const data = {
        type: 'PING',
        orderType: this.data.status
      };
      
      let len = this.data.orderList.length;
      if (len > 0) {
          data.maxId = this.data.orderList[0].order.id;
          data.minId = this.data.orderList[len-1].order.id;
          data.status = [];
          for(let i=0; i<len; i++){
            data.status.push({
              id: this.data.orderList[i].order.id,
              orderStatus: this.data.orderList[i].order.orderStatus
            });
          }
      }
      
      socket.send({
        data:JSON.stringify(data)
      });
    }, 15000)

    this.data.socketHandler = socket;
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.refreshListAdmin(this.data.status, true);
    this.connectWebSocket();
  
    // 收到新消息，播放提示音
    innerAudioContext = wx.createInnerAudioContext({
      useWebAudioImplement: true // 是否使用 WebAudio 作为底层音频驱动，默认关闭。对于短音频、播放频繁的音频建议开启此选项，开启后将获得更优的性能表现。由于开启此选项后也会带来一定的内存增长，因此对于长音频建议关闭此选项
    })

    this.enableBackgroundRun();
  },

  enableBackgroundRun(){
    // backgroundAudioManager = wx.getBackgroundAudioManager();
    // backgroundAudioManager.src = app.data.global_urls.musics[0];
    // backgroundAudioManager.play();

    // const backgroundAudioManager = wx.getBackgroundAudioManager()

    // backgroundAudioManager.title = '背景音乐'
    // backgroundAudioManager.epname = '此时此刻'
    // backgroundAudioManager.singer = ''
    // backgroundAudioManager.coverImgUrl = 'http://y.gtimg.cn/music/photo_new/T002R300x300M000003rsKF44GyaSk.jpg?max_age=2592000'
    // 设置了 src 之后会自动播放
    // backgroundAudioManager.src = app.data.global_urls.musics[0];
    // backgroundAudioManager.pause();
  },

  retryConnectWebSocket(){
    if(!this.data.websocketConnecting){
      this.connectWebSocket();
    }
  },

  finishOrder(e){
    let index = e.currentTarget.dataset.index;
    var that = this;
    orderService.finishOrderPromise(this.data.orderList[index].order.orderNo).then((res)=>{
      console.log(that.data.orderList)
      // 如果是全部页面，则不删除
      that.data.orderList[index].order = res.data;
      if(that.data.status !== -1){
        that.data.orderList.splice(index, 1);
      }
      console.log(that.data.orderList)
      that.setData({
        orderList: that.data.orderList
      })
    });
  },

  doRefundAdmin(e){
    let index = e.currentTarget.dataset.index;
    var that = this;
    wx.showModal({
      title: '警告',
      content: '你确定要退款吗？',
      complete: (res) => {
        if (res.confirm) {
          orderService.doRefundAdminPromise(this.data.orderList[index].order.orderNo).then((res)=>{
            console.log('----退款返回----', res)
            const key = `orderList[${index}].order.orderStatus`;
            this.setData({
              [key]: res.data.orderStatus,
            })
          });
        }
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
   this.data.socketHandler.close();
   if(this.data.websocketSendIntervalHandler){
    clearInterval(this.data.websocketSendIntervalHandler)
   }
   innerAudioContext.destroy()
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})